import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/model/jiayouList_model.dart';
import 'package:flutter_yres/pages/jiayouzhan/jyz_pay_page.dart';
import 'package:flutter/services.dart';
import '../../pages/jiayouzhan/goMap.dart';
import 'package:flutter_yres/tool/constant.dart';

class JYZDetailPage extends StatefulWidget {
  // String gasIds;
  JYZModelData model;
  JYZDetailPage({Key key, this.model}) : super(key: key);

  @override
  _JYZDetailPageState createState() => _JYZDetailPageState(model);
}

class _JYZDetailPageState extends State<JYZDetailPage> {
  // // 创建一个给native的channel (类似iOS的通知）
  static const methodChannel = const MethodChannel('com.pages.your/native_get');

  _iOSPushToVC(String url) async {
    await methodChannel.invokeMethod('iOSFlutter', url);
  }

  JYZModelData model;
  _JYZDetailPageState(this.model);

  // List list = [
  //   {"title": "影视特效", "type": 0,},
  //   {"title": "室内设计", "type": 1},
  //   {"title": "游戏原画", "type": 2},
  //   {"title": "次时代", "type": 3},
  //   {"title": "UI设计", "type": 4},
  //   {"title": "后期合成", "type": 5},
  // ];

  List oilPriceList = []; //油号
  int groupValue = 0;
  List gunNos = []; //油枪
  int gunValue = 0;
  String priceYfq = '';
  String oilName = '';
  var name;
  @override
  Widget build(BuildContext context) {
    // int groupValue=1;
    return Scaffold(
        appBar:
            AppBar(title: new Text('加油站'), centerTitle: true, actions: <Widget>[
          // new IconButton(icon: new Icon(Icons.collections), onPressed: () {})
        ]),
        backgroundColor: Colors.white,
        body: Container(
            child: CustomScrollView(slivers: <Widget>[
          SliverToBoxAdapter(
            child: Container(
                // height: bannerHeight,
                child: Column(
              children: <Widget>[
                Card(
                  elevation: ScreenUtil.getInstance().setWidth(10),
                  child: _buildListItem(),
                )
              ],
            )),
          ),
          SliverToBoxAdapter(
            child: Container(
                // height: bannerHeight,
                child: Column(
              children: <Widget>[
                Container(
                    margin:
                        EdgeInsets.all(ScreenUtil.getInstance().setWidth(28)),
                    child: Text('选择油号'))
              ],
            )),
          ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) -
                      ScreenUtil.getInstance().setWidth(20)) /
                  4,
              mainAxisSpacing: ScreenUtil.getInstance().setWidth(28),
              crossAxisSpacing: ScreenUtil.getInstance().setWidth(28),
              childAspectRatio: 2.6, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return listitem(context, index, 0);
              },
              childCount: oilPriceList.length,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
                // height: bannerHeight,
                child: Column(
              children: <Widget>[
                Container(
                    margin:
                        EdgeInsets.all(ScreenUtil.getInstance().setWidth(28)),
                    child: Text('选择油枪'))
              ],
            )),
          ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) -
                      ScreenUtil.getInstance().setWidth(20)) /
                  4,
              mainAxisSpacing: ScreenUtil.getInstance().setWidth(28),
              crossAxisSpacing: ScreenUtil.getInstance().setWidth(28),
              childAspectRatio: 2.6, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return listitem(context, index, 1);
              },
              childCount: gunNos.length,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
                // height: bannerHeight,
                child: Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Expanded(
                        child: Container(
                            height:
                                ScreenUtil.getInstance().setHeight(1334) * 0.06,
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setWidth(28),
                                ScreenUtil.getInstance().setWidth(28) * 2,
                                ScreenUtil.getInstance().setWidth(28),
                                0),
                            child: RaisedButton(
                              shape: RoundedRectangleBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)),
                              ),
                              //当前选中
                              color: Colors.blue,
                              onPressed: () {
                                //跳转支付页
                                var gasIds = this.model.gasid;
                                var url = Api.kJiaYouBaseURL +
                                    '?platformType=92652524&platformCode=' +
                                    name +
                                    '&gasId=' +
                                    gasIds +
                                    '&gunNo=' +
                                    gunValue.toString();

                                print(url);
                                // _iOSPushToVC(url);跳转原生界面

                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        //导航打开新视图
                                        builder: (context) => JYZPayPage(
                                              url: url,
                                              title: '订单支付',
                                            ) //打开第二个页面，并传值，传递值的名称是model
                                        ));
                              },
                              child: Text(
                                '确认',
                                style: TextStyle(color: Colors.white),
                              ),
                            )))
                  ],
                ),
                Container(
                    margin: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setWidth(28),
                        ScreenUtil.getInstance().setWidth(28),
                        ScreenUtil.getInstance().setWidth(28),
                        ScreenUtil.getInstance().setWidth(15)),
                    child: Text('若无您选择的油枪号，请联系油站工作人员')),
                Container(
                    margin: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setWidth(28),
                        0,
                        ScreenUtil.getInstance().setWidth(28),
                        ScreenUtil.getInstance().setWidth(28)),
                    child: Text('支付前请确认加油站是否正确'))
              ],
            )),
          ),
        ])));
  }

  Widget listitem(context, index, type) {
    //0是油号 1是油枪
    var value = type == 0 ? oilPriceList[index] : gunNos[index];
    var deviceSize = MediaQuery.of(context).size;
    return type == 0
        ? (groupValue == value['oilNo']
            ? RaisedButton(
                shape: StadiumBorder(),
                //当前选中
                color: Colors.blue,
                onPressed: () {
                  print('切换${value}');
                  updateGroupValue(value['oilNo']);
                  print(value['gunNos']);
                  setState(() {
                    priceYfq = value['priceYfq'];
                    gunNos = value['gunNos'];
                    oilName = value['oilName'];
                    //  gunValue = gunNos[0]['gunNo'];
                  });
                },
                child: Text(
                  value['oilName'],
                  style: TextStyle(color: Colors.white),
                ),
              )
            : OutlineButton(
                shape: StadiumBorder(),
                onPressed: () {
                  print('切换${value}');
                  updateGroupValue(value['oilNo']);
                  print(value['gunNos']);
                  setState(() {
                    priceYfq = value['priceYfq'];
                    gunNos = value['gunNos'];
                    gunValue = gunNos[0]['gunNo'];
                    oilName = value['oilName'];
                  });
                },
                child: Text(value['oilName']),
              ))
        : (gunValue == value['gunNo']
            ? RaisedButton(
                shape: StadiumBorder(),
                color: Colors.blue,
                onPressed: () {
                  print('切换${value}');
                  updateGunValue(value['gunNo']);
                },
                child: Text(
                  value['gunNo'].toString(),
                  style: TextStyle(color: Colors.white),
                ),
              )
            : OutlineButton(
                shape: StadiumBorder(),
                onPressed: () {
                  print('切换${value}');
                  updateGunValue(value['gunNo']);
                },
                child: Text(value['gunNo'].toString()),
              ));
  }

  Widget _buildListItem() {
    return Container(
        margin: EdgeInsets.fromLTRB(
            0, ScreenUtil.getInstance().setHeight(15), 0, 0),
        child: Column(
          children: <Widget>[
            Row(children: <Widget>[
              _leftImage(),
              Expanded(
                child: _rightColumn(),
              )
            ], crossAxisAlignment: CrossAxisAlignment.start),
            Divider(
              height: 1,
            )
          ],
        ));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage() {
    //左图
    var image = new Image(
        image: NetworkImage(model.gaslogosmall),
        width: ScreenUtil.getInstance().setHeight(150),
        height: ScreenUtil.getInstance().setHeight(150),
        fit: BoxFit.fill);
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn() {
    //右内容
    var title = Text(
      model.gasname,
      style: TextStyle(color: Colors.black, fontSize: 16.0),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(text: priceYfq, style: TextStyle(fontSize: 18.0)),
        TextSpan(text: '/升/' + oilName, style: TextStyle(fontSize: 12.0)),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var distance = RichText(
      text: TextSpan(style: TextStyle(fontSize: 13.0), children: [
        TextSpan(
            text:model.distance!=null?formatNum(double.parse(model.distance) / 1000, 2).toString() +
                'km':'',
            style: TextStyle(color: Colors.grey)),
        // TextSpan(text: '导航', style: TextStyle(color: Colors.orange)),
      ]),
    );
    var address = Text(
      model.provincename + model.cityname + model.countyname + model.gasaddress,
      style: TextStyle(color: Colors.grey, fontSize: 13.0),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        Row(
          children: <Widget>[
            _pd(price, l: 10, t: 0, r: 10, b: 8),
            Expanded(
              child: distance,
            ),
            GestureDetector(
                onTap: () {
                  print( model.gasaddresslongitude);
                  print( model.gasaddresslatitude);
                  showDialog(
                      context: context,
                      builder: (context) {
                        return new SimpleDialog(
                          title: new Text("选择地图"),
                          children: <Widget>[
                            new SimpleDialogOption(
                              child: new Text("高德地图"),
                              onPressed: () {
                                MapUtil.gotoAMap(
                                    model.gasaddresslongitude,
                                    model.gasaddresslatitude,
                                    model.gasaddress
                                    );
                              },
                            ),
                            new SimpleDialogOption(
                              child: new Text("百度地图"),
                              onPressed: () {
                                MapUtil.gotoBaiduMap(
                                   model.gasaddresslongitude,
                                    model.gasaddresslatitude,
                                    model.gasaddress
                                    );
                              },
                            ),
                            // new SimpleDialogOption(
                            //   child: new Text("腾讯地图"),
                            //   onPressed: () {
                            //     MapUtil.gotoTencentMap(
                            //         model.gasaddresslongitude,
                            //         model.gasaddresslatitude,
                            //         model.gasaddress
                            //         );
                            //   },
                            // ),
                            new SimpleDialogOption(
                              child: new Text("取消"),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      });
                },
                child: Container(
                    margin: EdgeInsets.only(
                        right: ScreenUtil.getInstance().setWidth(10)),
                    child: Text(
                      '导航',
                      style: TextStyle(
                          color: mainColor,
                          fontSize: ScreenUtil.getInstance().setSp(30)),
                    )))
          ],
        ),
        _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  void updateGroupValue(int v) {
    setState(() {
      groupValue = v;
      print(v);
    });
  }

  void updateGunValue(int v) {
    setState(() {
      gunValue = v;
      print(v);
    });
  }

  @override
  void initState() {
    _getLoginMsg();
    super.initState();
  }

  void _getLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    name = preferences.get("name");
    if (name == null || name == '') {
      //未登陆
      Navigator.of(context).pushNamed("login");
    } else {
      _getGasDetail(this.model.gasid, name);
    }
  }

  // kGas_detailURL
  _getGasDetail(gasIds, phone) async {
    FormData data = new FormData.fromMap({'gasIds': gasIds, 'phone': phone});
    Response<String> response =
        await HttpUtil().post(Api.kGas_detailURL, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 1) {
      if (mounted) {
        List result = userMap['data']['result'];
        Map result1 = result[0];
        List theoilPriceList = result1['oilPriceList'];
        setState(() {
          oilPriceList = theoilPriceList;
          priceYfq = theoilPriceList[0]['priceYfq'];
          oilName = theoilPriceList[0]['oilName'];
          groupValue = theoilPriceList[0]['oilNo'];
          gunNos = theoilPriceList[0]['gunNos'];
          gunValue = gunNos[0]['gunNo'];
        });
      }
    }
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      //小数点后有几位小数
      return (num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    } else {
      return (num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    }
  }
}
